<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>商家中心 - 商品管理</title>

    <!-- 外部资源加载顺序修正：先加载Vue核心库 -->
    <script src="../js/vue.js"></script>
    <script src="../js/axios.min.js"></script>
    <script src="../js/common.js"></script>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">

    <!-- 自定义 Tailwind 配置 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        success: '#00B42A',
                        warning: '#FF7D00',
                        danger: '#F53F3F',
                        gray: {
                            100: '#F2F3F5',
                            200: '#E5E6EB',
                            300: '#C9CDD4',
                            400: '#86909C',
                            500: '#4E5969',
                            600: '#272E3B',
                            700: '#1D2129',
                        }
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                },
            }
        }
    </script>

    <!-- 自定义工具类 -->
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto { content-visibility: auto; }
            .btn-primary { @apply bg-primary hover:bg-primary/90 text-white font-medium py-2 px-4 rounded-lg transition-all duration-200; }
            .btn-success { @apply bg-success hover:bg-success/90 text-white font-medium py-2 px-4 rounded-lg transition-all duration-200; }
            .btn-warning { @apply bg-warning hover:bg-warning/90 text-white font-medium py-2 px-4 rounded-lg transition-all duration-200; }
            .btn-danger { @apply bg-danger hover:bg-danger/90 text-white font-medium py-2 px-4 rounded-lg transition-all duration-200; }
            .btn-outline { @apply border border-gray-300 hover:border-primary text-gray-600 hover:text-primary font-medium py-2 px-4 rounded-lg transition-all duration-200; }
            .table-cell-ellipsis { @apply overflow-hidden text-ellipsis whitespace-nowrap; }
            .loading-skeleton { @apply bg-gray-100 animate-pulse rounded; }
            /* 分页相关工具类 */
            .page-item { @apply w-10 h-10 flex items-center justify-center rounded-lg transition-all duration-200 text-sm; }
            .page-item-active { @apply bg-primary text-white font-medium; }
            .page-item-disabled { @apply opacity-50 cursor-not-allowed text-gray-400; }
            .page-item-hover { @apply hover:bg-gray-100 hover:text-primary; }
        }
    </style>

    <!-- 关键修复：v-cloak样式确保未编译模板不显示 -->
    <style>
        [v-cloak] {
            display: none !important;
        }
    </style>
</head>

<!-- 关键修复：添加v-cloak指令 -->
<body class="bg-gray-100 min-h-screen flex flex-col" >
<div id="app" v-cloak>
    <!-- 顶部导航 -->
    <header class="sticky top-0 z-50 bg-white shadow-sm">
        <div class="container mx-auto px-4 py-3 flex justify-between items-center">
            <div class="flex items-center" >
                <i class="fa fa-briefcase text-primary text-2xl mr-2"></i>
                <h1 class="text-xl font-bold text-gray-700">商家管理中心</h1>
            </div>
            <div class="flex items-center gap-4">
                <!-- 消息通知 -->
                <div class="relative">
                    <button class="flex items-center text-gray-600 hover:text-primary transition-colors">
                        <i class="fa fa-bell-o text-lg"></i>
                        <span class="absolute -top-1 -right-1 bg-danger text-white text-xs w-4 h-4 rounded-full flex items-center justify-center" v-if="merchantInfo.unreadMsgCount > 0">
                        {{ merchantInfo.unreadMsgCount }}
                    </span>
                    </button>
                </div>

                <!-- 退出登录 -->
                <a href="../index.html"><button class="text-gray-600 hover:text-danger transition-colors" onclick="util.logout()">
                    <i class="fa fa-sign-out"></i>
                    <span class="ml-1">退出登录</span>
                </button></a>
            </div>
        </div>
    </header>

    <!-- 主体内容：侧边栏 + 主内容区 -->
    <div class="flex-grow flex">
        <!-- 侧边栏导航 -->
        <aside class="w-64 bg-white shadow-sm h-[calc(100vh-64px)] sticky top-16">
            <nav class="py-4">
                <div class="px-4 py-2 text-xs font-medium text-gray-400">核心功能</div>
                <a href="dashboard.html" class="flex items-center px-4 py-3 text-gray-600 hover:bg-gray-50 hover:text-primary transition-colors">
                    <i class="fa fa-tachometer mr-3"></i>
                    <span>仪表盘</span>
                </a>
                <a href="product-list.html" class="flex items-center px-4 py-3 text-primary bg-primary/5 border-l-4 border-primary">
                    <i class="fa fa-cubes mr-3"></i>
                    <span>商品管理</span>
                </a>
                <a href="order-list.html" class="flex items-center px-4 py-3 text-gray-600 hover:bg-gray-50 hover:text-primary transition-colors">
                    <i class="fa fa-list-alt mr-3"></i>
                    <span>订单管理</span>
                </a>
                <div class="px-4 py-2 mt-4 text-xs font-medium text-gray-400">店铺设置</div>
                <a href="shop-setting.html" class="flex items-center px-4 py-3 text-gray-600 hover:bg-gray-50 hover:text-primary transition-colors">
                    <i class="fa fa-cog mr-3"></i>
                    <span>店铺设置</span>
                </a>
                <a href="account-setting.html" class="flex items-center px-4 py-3 text-gray-600 hover:bg-gray-50 hover:text-primary transition-colors">
                    <i class="fa fa-user mr-3"></i>
                    <span>账号设置</span>
                </a>
            </nav>
        </aside>

        <!-- 主内容区 -->
        <main class="flex-grow p-6">
            <!-- 页面标题与操作区 -->
            <div class="mb-6 flex flex-col md:flex-row md:justify-between md:items-center gap-4">
                <div>
                    <h2 class="text-xl font-bold text-gray-700">商品管理</h2>
                    <p class="text-gray-400 mt-1">管理商品信息、库存、上下架状态</p>
                </div>
                <div class="flex gap-3">
                    <button class="btn-outline" v-if="selectedProductIds.length > 0" @click="batchChangeStatus">
                        <i class="fa fa-refresh mr-1"></i>
                        <span>{{ batchStatusText }}</span>
                    </button>
                    <button class="btn-danger" v-if="selectedProductIds.length > 0" @click="showBatchDeleteModal">
                        <i class="fa fa-trash mr-1"></i>
                        <span>批量删除</span>
                    </button>
                    <a href="product-add.html" class="btn-primary flex items-center justify-center">
                        <i class="fa fa-plus mr-2"></i>
                        <span>新增商品</span>
                    </a>
                </div>
            </div>

            <!-- 搜索与筛选区 -->
            <div class="bg-white rounded-xl p-6 shadow-sm mb-6">
                <form @submit.prevent="handleSearch" class="grid grid-cols-1 md:grid-cols-4 gap-4">
                    <!-- 商品名称搜索 -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">商品名称</label>
                        <div class="relative">
                        <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-500">
                            <i class="fa fa-search"></i>
                        </span>
                            <input
                                    type="text"
                                    placeholder="请输入商品名称"
                                    class="w-full pl-10 pr-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/30 focus:border-primary focus:outline-none transition-all"
                                    v-model="searchForm.name"
                            >
                        </div>
                    </div>

                    <!-- 类目筛选 -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">商品类目</label>
                        <div class="relative">
                        <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-500">
                            <i class="fa fa-th-list"></i>
                        </span>
                            <select
                                    class="w-full pl-10 pr-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/30 focus:border-primary focus:outline-none transition-all appearance-none bg-white"
                                    v-model="searchForm.categoryId"
                                    v-if="categoryList.length > 0"
                            >
                                <option value="">全部类目</option>
                                <option v-for="category in categoryList" :key="category.id" :value="category.id">
                                    {{ category }}
                                </option>
                            </select>
                            <div class="w-full pl-10 pr-3 py-2 loading-skeleton" v-else>加载中...</div>
                            <span class="absolute inset-y-0 right-0 flex items-center pr-3 text-gray-500 pointer-events-none">
                            <i class="fa fa-angle-down"></i>
                        </span>
                        </div>
                    </div>

                    <!-- 品牌筛选 -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">商品品牌</label>
                        <div class="relative">
                        <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-500">
                            <i class="fa fa-tag"></i>
                        </span>
                            <select
                                    class="w-full pl-10 pr-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/30 focus:border-primary focus:outline-none transition-all appearance-none bg-white"
                                    v-model="searchForm.brandId"
                                    v-if="brandList.length > 0"
                            >
                                <option value="">全部品牌</option>
                                <option v-for="brand in brandList" :key="brand.id" :value="brand.id">
                                    {{ brand }}
                                </option>
                            </select>
                            <div class="w-full pl-10 pr-3 py-2 loading-skeleton" v-else>加载中...</div>
                            <span class="absolute inset-y-0 right-0 flex items-center pr-3 text-gray-500 pointer-events-none">
                            <i class="fa fa-angle-down"></i>
                        </span>
                        </div>
                    </div>

                    <!-- 状态筛选 -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">商品状态</label>
                        <div class="relative">
                        <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-500">
                            <i class="fa fa-check-circle"></i>
                        </span>
                            <select
                                    class="w-full pl-10 pr-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/30 focus:border-primary focus:outline-none transition-all appearance-none bg-white"
                                    v-model="searchForm.status"
                            >
                                <option value="">全部状态</option>
                                <option value="1">正常（上架）</option>
                                <option value="2">下架</option>
                                <option value="3">已删除</option>
                            </select>
                            <span class="absolute inset-y-0 right-0 flex items-center pr-3 text-gray-500 pointer-events-none">
                            <i class="fa fa-angle-down"></i>
                        </span>
                        </div>
                    </div>

                    <!-- 搜索按钮 -->
                    <div class="md:col-span-4 flex justify-end gap-3 pt-2">
                        <button type="button" class="btn-outline" @click="resetSearch">
                            <i class="fa fa-refresh mr-1"></i>
                            <span>重置</span>
                        </button>
                        <button type="submit" class="btn-primary" :disabled="isSearching">
                            <i class="fa fa-search mr-1"></i>
                            <span v-if="!isSearching">搜索</span>
                            <span v-if="isSearching">搜索中...</span>
                        </button>
                    </div>
                </form>
            </div>

            <!-- 商品列表（后端数据渲染） -->
            <div class="bg-white rounded-xl shadow-sm overflow-hidden">
                <!-- 加载状态 -->
                <div class="p-10 text-center" v-if="isLoading && productList.length === 0">
                    <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-primary mb-4"></div>
                    <p class="text-gray-500">正在加载商品数据...</p>
                </div>

                <!-- 空状态 -->
                <div class="p-10 text-center" v-if="!isLoading && productList.length === 0">
                    <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-gray-100 text-gray-400 mb-4">
                        <i class="fa fa-cube text-2xl"></i>
                    </div>
                    <h3 class="text-lg font-medium text-gray-700">暂无商品数据</h3>
                    <p class="text-gray-500 mt-2">没有找到符合条件的商品，请尝试调整筛选条件或新增商品</p>
                    <a href="product-add.html" class="inline-block mt-4 btn-primary">
                        <i class="fa fa-plus mr-1"></i>新增商品
                    </a>
                </div>

                <!-- 商品表格 -->
                <div class="overflow-x-auto" v-if="productList.length > 0">
                    <table class="w-full text-left">
                        <thead>
                        <tr class="border-b border-gray-200 bg-gray-50">
                            <th class="py-4 px-6 text-sm font-medium text-gray-500 w-12">
                                <input type="checkbox" class="h-4 w-4 text-primary border-gray-300 rounded focus:ring-primary/30"
                                       @change="selectAllProducts" :checked="isAllSelected">
                            </th>
                            <th class="py-4 px-6 text-sm font-medium text-gray-500">商品图片</th>
                            <th class="py-4 px-6 text-sm font-medium text-gray-500">商品信息</th>
                            <th class="py-4 px-6 text-sm font-medium text-gray-500">价格</th>
                            <th class="py-4 px-6 text-sm font-medium text-gray-500">库存</th>
                            <th class="py-4 px-6 text-sm font-medium text-gray-500">状态</th>
                            <th class="py-4 px-6 text-sm font-medium text-gray-500">操作</th>
                        </tr>
                        </thead>
                        <tbody>
                        <!-- 商品列表项（循环渲染） -->
                        <tr class="border-b border-gray-100 hover:bg-gray-50 transition-colors"
                            v-for="product in productList" :key="product.id"
                            :class="{ 'opacity-50': product.isProcessing }">
                            <td class="py-4 px-6">
                                <input
                                        type="checkbox"
                                        class="h-4 w-4 text-primary border-gray-300 rounded focus:ring-primary/30"
                                        v-model="selectedProductIds"
                                        :value="product.id"
                                        :disabled="product.isProcessing"
                                >
                            </td>
                            <td class="py-4 px-6">
                                <img :src="product.image" alt="商品图片" class="w-16 h-16 object-cover rounded"
                                     :class="{ 'opacity-60': product.status === 2 }">
                            </td>
                            <td class="py-4 px-6">
                                <div class="font-medium text-gray-700 table-cell-ellipsis w-48"
                                     :class="{ 'line-through': product.status === 2 }">
                                    {{ product.name }}
                                </div>
                                <div class="text-sm text-gray-500 mt-1">
                                    <span class="mr-3">类目：{{ getCategoryName(product.categoryId) }}</span>
                                    <span>品牌：{{ getBrandName(product.brandId) }}</span>
                                </div>
                                <div class="text-sm text-gray-500 mt-1" v-if="product.specs && product.specs.length > 0">
                                    规格：{{ product.specs.map(spec => `${spec.name}：${spec.value}`).join(' / ') }}
                                </div>
                            </td>
                            <td class="py-4 px-6 text-sm font-medium text-gray-700">¥{{ product.price.toFixed(2) }}</td>
                            <td class="py-4 px-6 text-sm text-gray-600">
                                <span :class="{ 'text-danger': product.stock <= 10 }">{{ product.stock }}</span>
                                <span class="text-gray-400 text-xs ml-1" v-if="product.stock <= 10">库存偏低</span>
                            </td>
                            <td class="py-4 px-6">
                            <span
                                    class="px-2 py-1 text-xs rounded-full"
                                    :class="product.status === 1 ? 'bg-success/10 text-success' : 'bg-gray-100 text-gray-500'"
                            >
                                {{ product.status === 1 ? '正常（上架）' : '已下架' }}
                            </span>
                            </td>
                            <td class="py-4 px-6">
                                <div class="flex gap-2">
                                    <!-- 编辑商品 -->
                                    <a :href="`product-edit.html?id=${product.id}`"
                                       class="text-primary hover:underline text-sm flex items-center"
                                       :disabled="product.isProcessing"
                                       :class="{ 'opacity-50 cursor-not-allowed': product.isProcessing }">
                                        <i class="fa fa-pencil mr-1"></i>编辑
                                    </a>

                                    <!-- 状态切换（上架/下架） -->
                                    <button
                                            class="text-sm flex items-center hover:underline"
                                            :class="product.status === 1 ? 'text-warning' : 'text-success'"
                                            @click="toggleProductStatus(product)"
                                            :disabled="product.isProcessing"
                                            :class="{ 'opacity-50 cursor-not-allowed': product.isProcessing }"
                                    >
                                        <i :class="product.status === 1 ? 'fa fa-arrow-down mr-1' : 'fa fa-arrow-up mr-1'"></i>
                                        <span>{{ product.status === 1 ? '下架' : '上架' }}</span>
                                    </button>

                                    <!-- 删除商品 -->
                                    <button
                                            class="text-danger hover:underline text-sm flex items-center"
                                            @click="showDeleteModal(product.id)"
                                            :disabled="product.isProcessing"
                                            :class="{ 'opacity-50 cursor-not-allowed': product.isProcessing }"
                                    >
                                        <i class="fa fa-trash mr-1"></i>删除
                                    </button>
                                </div>
                            </td>
                        </tr>
                        </tbody>
                    </table>
                </div>

                <!-- 优化后的分页组件 -->
                <div class="px-6 py-4 border-t border-gray-200 flex flex-col md:flex-row md:justify-between md:items-center gap-4"
                     v-if="productList.length > 0">
                    <div class="text-sm text-gray-500">
                        共 <span class="font-medium text-gray-700">{{ pagination.total }}</span> 个商品，
                        当前显示第 <span class="font-medium text-gray-700">{{ pagination.start }}页，</span> <span class="font-medium text-gray-700">共{{ pagination.totalPages }}</span> 页
                    </div>

                    <!-- 优化后的分页条 -->
                    <div class="flex items-center gap-1">
                        <!-- 首页按钮 -->
                        <button
                                class="page-item page-item-hover"
                                :class="{ 'page-item-disabled': pagination.currentPage === 1 }"
                                :disabled="pagination.currentPage === 1"
                                @click="changePage(1)"
                        >
                            <i class="fa fa-angle-double-left"></i>
                        </button>

                        <!-- 上一页按钮 -->
                        <button
                                class="page-item page-item-hover"
                                :class="{ 'page-item-disabled': pagination.currentPage === 1 }"
                                :disabled="pagination.currentPage === 1"
                                @click="changePage(pagination.currentPage - 1)"
                        >
                            <i class="fa fa-angle-left"></i>
                        </button>

                        <!-- 页码按钮 -->
                        <button
                                v-for="page in pagination.pages"
                                :key="page"
                                class="page-item"
                                :class="{
                            'page-item-active': page === pagination.currentPage,
                            'page-item-hover': page !== pagination.currentPage && page !== '...',
                            'cursor-default': page === '...'
                        }"
                                @click="changePage(page)"
                                :disabled="page === '...'"
                        >
                            {{ page }}
                        </button>

                        <!-- 下一页按钮 -->
                        <button
                                class="page-item page-item-hover"
                                :class="{ 'page-item-disabled': pagination.currentPage === pagination.totalPages }"
                                :disabled="pagination.currentPage === pagination.totalPages"
                                @click="changePage(pagination.currentPage + 1)"
                        >
                            <i class="fa fa-angle-right"></i>
                        </button>

                        <!-- 末页按钮 -->
                        <button
                                class="page-item page-item-hover"
                                :class="{ 'page-item-disabled': pagination.currentPage === pagination.totalPages }"
                                :disabled="pagination.currentPage === pagination.totalPages"
                                @click="changePage(pagination.totalPages)"
                        >
                            <i class="fa fa-angle-double-right"></i>
                        </button>

                        <!-- 页码跳转 -->
                        <div class="ml-4 flex items-center gap-2">
                            <span class="text-sm text-gray-500">跳至</span>
                            <input
                                    type="number"
                                    v-model.number="jumpPage"
                                    min="1"
                                    :max="pagination.totalPages"
                                    class="w-16 h-10 text-center border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/30 focus:border-primary focus:outline-none transition-all text-sm"
                                    @keydown.enter="handleJumpPage"
                            >
                            <span class="text-sm text-gray-500">页</span>
                            <button
                                    class="btn-outline px-3 py-1 h-10 text-sm"
                                    @click="handleJumpPage"
                            >
                                确定
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>

    <!-- 页脚 -->
    <footer class="bg-white border-t border-gray-200 py-4 text-center text-sm text-gray-500">
        © 2025 ShopEasy 电商平台 - 商家管理系统，保留所有权利。
    </footer>

    <!-- 单个商品删除确认弹窗 -->
    <div class="fixed inset-0 bg-black/50 z-50 flex items-center justify-center" v-if="showDeleteModalFlag">
        <div class="bg-white rounded-xl p-6 w-full max-w-md transform transition-all">
            <div class="text-center mb-4">
                <div class="inline-flex items-center justify-center w-12 h-12 rounded-full bg-danger/10 text-danger mb-4">
                    <i class="fa fa-exclamation-circle text-xl"></i>
                </div>
                <h3 class="text-lg font-bold text-gray-700">确认删除商品？</h3>
                <p class="text-gray-500 mt-2">删除后商品数据将无法恢复，请谨慎操作！</p>
            </div>
            <div class="flex gap-3">
                <button class="flex-1 btn-outline" @click="hideDeleteModal">取消</button>
                <button class="flex-1 btn-danger" @click="confirmDelete" :disabled="isDeleting">
                    <i class="fa fa-trash mr-1"></i>
                    <span v-if="!isDeleting">确认删除</span>
                    <span v-if="isDeleting">删除中...</span>
                </button>
            </div>
        </div>
    </div>

    <!-- 批量删除确认弹窗 -->
    <div class="fixed inset-0 bg-black/50 z-50 flex items-center justify-center" v-if="showBatchDeleteModalFlag">
        <div class="bg-white rounded-xl p-6 w-full max-w-md transform transition-all">
            <div class="text-center mb-4">
                <div class="inline-flex items-center justify-center w-12 h-12 rounded-full bg-danger/10 text-danger mb-4">
                    <i class="fa fa-exclamation-triangle text-xl"></i>
                </div>
                <h3 class="text-lg font-bold text-gray-700">确认批量删除？</h3>
                <p class="text-gray-500 mt-2">您即将删除 <span class="font-medium text-danger">{{ selectedProductIds.length }}</span> 个商品，删除后数据将无法恢复！</p>
            </div>
            <div class="flex gap-3">
                <button class="flex-1 btn-outline" @click="hideBatchDeleteModal">取消</button>
                <button class="flex-1 btn-danger" @click="confirmBatchDelete" :disabled="isBatchDeleting">
                    <i class="fa fa-trash mr-1"></i>
                    <span v-if="!isBatchDeleting">确认删除</span>
                    <span v-if="isBatchDeleting">删除中...</span>
                </button>
            </div>
        </div>
    </div>

    <!-- 提示消息组件 -->
    <div class="fixed top-4 right-4 z-50 flex flex-col gap-3" v-if="notifications.length > 0">
        <div class="bg-white shadow-lg rounded-lg p-4 max-w-sm transform transition-all duration-300 flex items-start gap-3"
             v-for="(notification, index) in notifications" :key="index"
             :class="notification.type === 'success' ? 'border-l-4 border-success' :
                      notification.type === 'error' ? 'border-l-4 border-danger' :
                      'border-l-4 border-primary'">
            <i class="fa" :class="notification.type === 'success' ? 'fa-check-circle text-success' :
                                 notification.type === 'error' ? 'fa-times-circle text-danger' :
                                 'fa-info-circle text-primary'"></i>
            <div class="flex-1">
                <h4 class="font-medium text-gray-700">{{ notification.title }}</h4>
                <p class="text-sm text-gray-500 mt-1">{{ notification.message }}</p>
            </div>
            <button class="text-gray-400 hover:text-gray-600" @click="removeNotification(index)">
                <i class="fa fa-times"></i>
            </button>
        </div>
    </div>
</div>

    <script>
        // 确保在DOM加载完成后初始化Vue
        document.addEventListener('DOMContentLoaded', function() {
            // 全局配置axios
/*            axios.defaults.baseURL = '/api';
            axios.defaults.headers.common['Authorization'] = `Bearer ${localStorage.getItem('token')}`;

            // 添加响应拦截器处理错误
            axios.interceptors.response.use(
                response => response,
                error => {
                    // 未登录或token过期
                    if (error.response && error.response.status === 401) {
                        localStorage.removeItem('token');
                        window.location.href = 'login.html';
                        return Promise.reject(error);
                    }

                    // 其他错误统一处理
                    const message = error.response?.data?.message || '操作失败，请重试';
                    vm.addNotification('错误', message, 'error');
                    return Promise.reject(error);
                }
            );*/

            // 初始化Vue实例
            window.vm = new Vue({
                el: '#app',
                data() {
                    return {
                        // 商家信息
                        merchantInfo: {
                            shopName: '',
                            avatarUrl: '',
                            unreadMsgCount: 0
                        },

                        // 商品列表数据
                        productList: [],

                        // 类目和品牌列表
                        categoryList: [],
                        brandList: [],

                        // 搜索表单数据
                        searchForm: {
                            name: '',
                            categoryId: '',
                            brandId: '',
                            status: ''
                        },

                        // 分页信息
                        pagination: {
                            currentPage: 1,
                            pageSize: 10,
                            total: 0,
                            totalPages: 0,
                            start: 0,
                            end: 0,
                            pages: []
                        },

                        // 页码跳转
                        jumpPage: 1,

                        // 选中的商品ID
                        selectedProductIds: [],

                        // 状态标记
                        isLoading: false,
                        isSearching: false,
                        isDeleting: false,
                        isBatchDeleting: false,

                        // 弹窗控制
                        showDeleteModalFlag: false,
                        currentDeleteId: '',
                        showBatchDeleteModalFlag: false,

                        // 通知消息
                        notifications: []
                    };
                },

                computed: {
                    // 判断是否全选
                    isAllSelected() {
                        return this.productList.length > 0 &&
                            this.selectedProductIds.length === this.productList.length &&
                            this.productList.every(p => !p.isProcessing);
                    },

                    // 批量操作状态文本
                    batchStatusText() {
                        // 检查选中的商品是否全部为同一状态
                        const firstStatus = this.productList.find(p => this.selectedProductIds.includes(p.id))?.status;
                        const allSameStatus = this.selectedProductIds.every(id => {
                            const product = this.productList.find(p => p.id === id);
                            return product && product.status === firstStatus;
                        });

                        if (allSameStatus) {
                            return firstStatus === 1 ? '批量下架' : '批量上架';
                        }
                        return '批量操作';
                    }
                },

                watch: {
                    // 监听当前页码变化，同步到跳转输入框
                    'pagination.currentPage'(newVal) {
                        this.jumpPage = newVal;
                    }
                },

                created() {
                    // 初始化页面数据
                    // this.loadMerchantInfo();
                    this.loadCategories();
                    this.loadBrands();
                    this.loadProducts();
                },

                methods: {
/*                    // 加载商家信息
                    loadMerchantInfo() {
                        axios.get('/merchant/info')
                            .then(response => {
                                this.merchantInfo = response.data.data;
                            })
                            .catch(error => {
                                console.error('加载商家信息失败', error);
                            });
                    },*/

                    // 加载商品类目
                    loadCategories() {
                        axios.get('/items/categories')
                            .then(response => {
                                this.categoryList = response.data;
                            })
                            .catch(error => {
                                console.error('加载类目失败', error);
                                this.addNotification('错误', '加载商品类目失败', 'error');
                            });
                    },

                    // 加载商品品牌
                    loadBrands() {
                        axios.get('/items/brands')
                            .then(response => {
                                this.brandList = response.data;
                            })
                            .catch(error => {
                                console.error('加载品牌失败', error);
                                this.addNotification('错误', '加载商品品牌失败', 'error');
                            });
                    },

                    // 加载商品列表
                    loadProducts() {
                        this.isLoading = true;

                        // 构建请求参数
                        const params = {
                            page: this.pagination.currentPage,
                            pageSize: this.pagination.pageSize,
                            ...this.searchForm
                        };

                        axios.get('/items/products', { params })
                            .then(response => {
                                const data = response.data;
                                this.productList = data.records.map(item => ({
                                    ...item,
                                    isProcessing: false // 添加处理状态标记
                                }));

                                // 更新分页信息
                                this.pagination.total = data.total;
                                this.pagination.totalPages = data.pages;
                                this.pagination.start = data.currentPage;
                                this.pagination.end = data.size;

                                // 生成页码数组
                                this.generatePageNumbers();

                                // 同步跳转页码
                                this.jumpPage = this.pagination.currentPage;
                            })
                            .catch(error => {
                                console.error('加载商品失败', error);
                                this.addNotification('错误', '加载商品列表失败', 'error');
                            })
                            .finally(() => {
                                this.isLoading = false;
                            });
                    },

                    // 生成页码数组
                    generatePageNumbers() {
                        const pages = [];
                        const totalPages = this.pagination.totalPages;
                        const currentPage = this.pagination.currentPage;

                        // 总是显示第一页
                        pages.push(1);

                        // 处理中间页码
                        if (currentPage > 3) {
                            pages.push('...');
                        }
                        for (let i = Math.max(2, currentPage - 2); i <= Math.min(totalPages - 1, currentPage + 2); i++) {
                            pages.push(i);
                        }

                        // 处理最后几页
                        if (currentPage < totalPages - 2) {
                            pages.push('...');
                        }

                        // 总是显示最后一页（如果不是第一页）
                        if (totalPages > 1) {
                            pages.push(totalPages);
                        }

                        this.pagination.pages = pages;
                    },

                    // 切换页码
                    changePage(page) {
                        // 忽略无效页码和当前页
                        if (page === '...' || page === this.pagination.currentPage) return;

                        this.pagination.currentPage = page;
                        this.loadProducts();

                        // 滚动到顶部
                        window.scrollTo(0, 0);
                    },

                    // 处理页码跳转
                    handleJumpPage() {
                        let page = parseInt(this.jumpPage);
                        // 验证页码有效性
                        if (isNaN(page) || page < 1) {
                            page = 1;
                        } else if (page > this.pagination.totalPages) {
                            page = this.pagination.totalPages;
                        }

                        if (page !== this.pagination.currentPage) {
                            this.pagination.currentPage = page;
                            this.loadProducts();
                            window.scrollTo(0, 0);
                        }
                    },

                    // 搜索商品
                    handleSearch() {
                        this.isSearching = true;
                        this.pagination.currentPage = 1; // 重置到第一页

                        setTimeout(() => {
                            this.loadProducts();
                            this.isSearching = false;
                        }, 300);
                    },

                    // 重置搜索条件
                    resetSearch() {
                        this.searchForm = {
                            name: '',
                            categoryId: '',
                            brandId: '',
                            status: ''
                        };
                        this.selectedProductIds = [];
                    },

                    // 全选/取消全选
                    selectAllProducts(e) {
                        if (e.target.checked) {
                            // 只选中可操作的商品
                            this.selectedProductIds = this.productList
                                .filter(p => !p.isProcessing)
                                .map(p => p.id);
                        } else {
                            this.selectedProductIds = [];
                        }
                    },

                    // 切换商品状态（上架/下架）
                    toggleProductStatus(product) {
                        // 设置处理状态
                        product.isProcessing = true;

                        const newStatus = product.status === 1 ? 2 : 1;
                        const statusText = newStatus === 1 ? '上架' : '下架';

                        axios.get(`/items/status/${product.id}`, { status: newStatus })
                            .then(response => {
                                product.status = newStatus;
                                this.addNotification('成功', `商品${statusText}成功`, 'success');
                            })
                            .catch(error => {
                                console.error(`商品${statusText}失败`, error);
                                this.addNotification('错误', `商品${statusText}失败`, 'error');
                            })
                            .finally(() => {
                                product.isProcessing = false;
                            });
                    },

                    // 批量切换状态
                    batchChangeStatus() {
                        if (this.selectedProductIds.length === 0) return;

                        // 确定目标状态
                        const firstProduct = this.productList.find(p => this.selectedProductIds.includes(p.id));
                        const targetStatus = firstProduct.status === 1 ? 2 : 1;
                        const statusText = targetStatus === 1 ? '上架' : '下架';

                        // 设置所有选中商品的处理状态
                        this.productList.forEach(p => {
                            if (this.selectedProductIds.includes(p.id)) {
                                p.isProcessing = true;
                            }
                        });

                        axios.put('/items/batch/status', {
                            ids: this.selectedProductIds,
                            status: targetStatus
                        })
                            .then(response => {
                                // 更新状态
                                this.productList.forEach(p => {
                                    if (this.selectedProductIds.includes(p.id)) {
                                        p.status = targetStatus;
                                    }
                                });

                                this.addNotification('成功', `已批量${statusText}${this.selectedProductIds.length}个商品`, 'success');
                                this.selectedProductIds = [];
                            })
                            .catch(error => {
                                console.error(`批量${statusText}失败`, error);
                                this.addNotification('错误', `批量${statusText}失败`, 'error');
                            })
                            .finally(() => {
                                // 清除处理状态
                                this.productList.forEach(p => {
                                    if (this.selectedProductIds.includes(p.id)) {
                                        p.isProcessing = false;
                                    }
                                });
                            });
                    },

                    // 显示删除弹窗
                    showDeleteModal(id) {
                        this.currentDeleteId = id;
                        this.showDeleteModalFlag = true;
                        document.body.style.overflow = 'hidden';
                    },

                    // 隐藏删除弹窗
                    hideDeleteModal() {
                        this.showDeleteModalFlag = false;
                        this.currentDeleteId = '';
                        document.body.style.overflow = '';
                    },

                    // 确认删除
                    confirmDelete() {
                        if (!this.currentDeleteId) return;

                        this.isDeleting = true;

                        // 找到对应的商品并标记处理状态
                        const product = this.productList.find(p => p.id === this.currentDeleteId);
                        if (product) {
                            product.isProcessing = true;
                        }

                        axios.delete(`/items/${this.currentDeleteId}`)
                            .then(response => {
                                this.addNotification('成功', '商品删除成功', 'success');

                                // 从列表中移除商品
                                this.productList = this.productList.filter(p => p.id !== this.currentDeleteId);

                                // 如果列表为空，重新加载
                                if (this.productList.length === 0 && this.pagination.currentPage > 1) {
                                    this.pagination.currentPage--;
                                    this.loadProducts();
                                }

                                this.hideDeleteModal();
                            })
                            .catch(error => {
                                console.error('删除商品失败', error);
                                this.addNotification('错误', '删除商品失败', 'error');
                            })
                            .finally(() => {
                                this.isDeleting = false;
                                if (product) {
                                    product.isProcessing = false;
                                }
                            });
                    },

                    // 显示批量删除弹窗
                    showBatchDeleteModal() {
                        if (this.selectedProductIds.length === 0) return;

                        this.showBatchDeleteModalFlag = true;
                        document.body.style.overflow = 'hidden';
                    },

                    // 隐藏批量删除弹窗
                    hideBatchDeleteModal() {
                        this.showBatchDeleteModalFlag = false;
                        document.body.style.overflow = '';
                    },

                    confirmBatchDelete() {
                        if (this.selectedProductIds.length === 0) return;

                        this.isBatchDeleting = true;

                        // 标记所有选中商品为处理中
                        this.productList.forEach(p => {
                            if (this.selectedProductIds.includes(p.id)) {
                                p.isProcessing = true;
                            }
                        });

                        axios.post('/items/batch/delete', this.selectedProductIds) // 发送数组而不是对象
                            .then(response => {
                                this.addNotification('成功', `已删除${this.selectedProductIds.length}个商品`, 'success');

                                // 从列表中移除已删除商品
                                this.productList = this.productList.filter(p => !this.selectedProductIds.includes(p.id));

                                // 如果列表为空，重新加载
                                if (this.productList.length === 0 && this.pagination.currentPage > 1) {
                                    this.pagination.currentPage--;
                                    this.loadProducts();
                                }

                                this.selectedProductIds = [];
                                this.hideBatchDeleteModal();
                            })
                            .catch(error => {
                                console.error('批量删除失败', error);
                                this.addNotification('错误', '批量删除失败', 'error');
                            })
                            .finally(() => {
                                this.isBatchDeleting = false;

                                // 清除处理状态
                                this.productList.forEach(p => {
                                    if (this.selectedProductIds.includes(p.id)) {
                                        p.isProcessing = false;
                                    }
                                });
                            });
                    },


                    // 添加通知消息
                    addNotification(title, message, type = 'info') {
                        this.notifications.push({ title, message, type });

                        // 3秒后自动移除
                        setTimeout(() => {
                            this.notifications.shift();
                        }, 3000);
                    },

                    // 手动移除通知
                    removeNotification(index) {
                        this.notifications.splice(index, 1);
                    },

                    // 获取类目名称
                    getCategoryName(id) {
                        const category = this.categoryList.find(c => c.id === id);
                        return category ? category.name : '未知类目';
                    },

                    // 获取品牌名称
                    getBrandName(id) {
                        const brand = this.brandList.find(b => b.id === id);
                        return brand ? brand.name : '未知品牌';
                    },

                    // 退出登录
/*                    logout() {
                        if (confirm('确定要退出登录吗？')) {
                            localStorage.removeItem('token');
                            window.location.href = 'login.html';
                        }
                    }*/
                }
            });
        });
    </script>

</body>
</html>
